package com.ruoyi.zxjd.conference.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.SmsUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.zxjd.common.CommonConstants;
import com.ruoyi.zxjd.common.domain.CommonUserVO;
import com.ruoyi.zxjd.common.mapper.CommonMapper;
import com.ruoyi.zxjd.conference.domain.ConferenceArrange;
import com.ruoyi.zxjd.conference.domain.ConferenceProgress;
import com.ruoyi.zxjd.conference.mapper.ConferenceArrangeMapper;
import com.ruoyi.zxjd.conference.service.IConferenceArrangeService;
import com.ruoyi.zxjd.work.domain.WorkHandle;
import com.ruoyi.zxjd.work.service.IWorkHandleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.constraints.Size;
import java.util.*;

/**
 * 会议安排Controller
 * 
 * @author lcc
 * @date 2021-02-07
 */
@Controller
@RequestMapping("/conference/arrange")
public class ConferenceArrangeController extends BaseController
{
    private String prefix = "conference/arrange";

    @Autowired
    private IConferenceArrangeService conferenceArrangeService;

    @Autowired
    private ISysUserService sysUserService;

    @Resource
    private CommonMapper commonMapper;

    @Resource
    private ConferenceArrangeMapper conferenceArrangeMapper;

    @Autowired
    private IWorkHandleService workHandleService;

    @RequiresPermissions("conference:arrange:view")
    @GetMapping()
    public String arrange()
    {
        return prefix + "/arrange";
    }

    /**
     * 查询会议安排列表
     */
    @RequiresPermissions("conference:arrange:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ConferenceArrange conferenceArrange)
    {
        startPage();
        List<ConferenceArrange> list = conferenceArrangeService.selectConferenceArrangeList(conferenceArrange);
        return getDataTable(list);
    }

    /**
     * 导出会议安排列表
     */
    @RequiresPermissions("conference:arrange:export")
    @Log(title = "会议安排", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ConferenceArrange conferenceArrange)
    {
        List<ConferenceArrange> list = conferenceArrangeService.selectConferenceArrangeList(conferenceArrange);
        ExcelUtil<ConferenceArrange> util = new ExcelUtil<ConferenceArrange>(ConferenceArrange.class);
        return util.exportExcel(list, "arrange");
    }

    /**
     * 新增会议安排
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存会议安排
     */
    @RequiresPermissions("conference:arrange:add")
    @Log(title = "会议安排", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ConferenceArrange conferenceArrange,MultipartFile file)
    {
        //默认为草稿
        conferenceArrange.setStatus("0");
        return toAjax(conferenceArrangeService.insertConferenceArrange(conferenceArrange));
    }

    /**
     * 新增保存（发布）会议安排
     */
    @RequiresPermissions("conference:arrange:add")
    @Log(title = "会议安排", businessType = BusinessType.INSERT)
    @PostMapping("/add1")
    @ResponseBody
    @Transactional
    public AjaxResult addSave1(ConferenceArrange conferenceArrange,MultipartFile file)
    {
        //默认为草稿先存入
        conferenceArrange.setStatus("0");
        conferenceArrangeService.insertConferenceArrange(conferenceArrange);
        //存入后获取主键
        return toAjax(conferenceArrangeService.updateStatusByArrangeId(conferenceArrange.getArrangeId(), CommonConstants.DRAFT));
    }

    /**
     * 修改会议安排
     */
    @GetMapping("/edit/{arrangeId}")
    public String edit(@PathVariable("arrangeId") Long arrangeId, ModelMap mmap)
    {
        ConferenceArrange conferenceArrange = conferenceArrangeService.selectConferenceArrangeById(arrangeId);
        mmap.put("conferenceArrange", conferenceArrange);
        return prefix + "/edit";
    }

    /**
     * 修改保存会议安排
     */
    @RequiresPermissions("conference:arrange:edit")
    @Log(title = "会议安排", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ConferenceArrange conferenceArrange,MultipartFile file)
    {
        //默认为草稿
        conferenceArrange.setStatus("0");
        //old会议
        ConferenceArrange conferenceArrange1 = conferenceArrangeService.selectConferenceArrangeById(conferenceArrange.getArrangeId());
        //会议主题
        String arrangeTheme = conferenceArrange1.getArrangeTheme();
        //会议发起部门
        String deptName = conferenceArrange1.getDeptName();

        String releaseScope = conferenceArrange1.getReleaseScope();
        String[] ids = new String[0];
        String[] userNames = releaseScope.split(" ");
        for (int i=0;i<userNames.length;i++){
            SysUser sysUser = sysUserService.selectUserByName(userNames[i]);
            ids = Arrays.copyOf(ids, ids.length + 1); // 数组增加一个长度
            ids[ids.length - 1] = sysUser.getUserId()+""; // 在增加的位置赋值需要添加的数据
        }
        conferenceArrange1.setUserIds(ids);
        String[] userIds = conferenceArrange1.getUserIds();
        List<CommonUserVO> list = null;

        if(CommonConstants.AllUSER.equals(releaseScope)){
            list = commonMapper.listActiveUser(null,null);
        }else{
            list = commonMapper.listActiveUserByIds(userIds);
        }
        if(StringUtils.isNotNull(list)) {
            if (StringUtils.equals(CommonConstants.PUBLISHED, conferenceArrange.getStatus())) {
                //短信提示
                if (StringUtils.equals(CommonConstants.TIPS, conferenceArrange1.getSmsTips())) {
                    AsyncManager.me().execute(createSmsTips(conferenceArrange1.getArrangeName(), list,conferenceArrange1));
                }
                //平台提示
                if (StringUtils.equals(CommonConstants.TIPS, conferenceArrange1.getWebsiteTips())) {
                    AsyncManager.me().execute(createWebsiteTips(list, 1));
                }
            }
        }
        return toAjax(conferenceArrangeService.updateConferenceArrange(conferenceArrange));
    }

    /**
     * 修改保存（发布）会议安排
     */
    @RequiresPermissions("conference:arrange:edit")
    @Log(title = "会议安排", businessType = BusinessType.UPDATE)
    @PostMapping("/edit1")
    @ResponseBody
    @Transactional
    public AjaxResult editSave1(ConferenceArrange conferenceArrange,MultipartFile file)
    {
        //默认为草稿
        conferenceArrange.setStatus("0");
        //old会议
        ConferenceArrange conferenceArrange1 = conferenceArrangeService.selectConferenceArrangeById(conferenceArrange.getArrangeId());
        //会议主题
        String arrangeTheme = conferenceArrange1.getArrangeTheme();
        //会议发起部门
        String deptName = conferenceArrange1.getDeptName();

        String releaseScope = conferenceArrange1.getReleaseScope();
        String[] ids = new String[0];
        String[] userNames = releaseScope.split(" ");
        for (int i=0;i<userNames.length;i++){
            SysUser sysUser = sysUserService.selectUserByName(userNames[i]);
            ids = Arrays.copyOf(ids, ids.length + 1); // 数组增加一个长度
            ids[ids.length - 1] = sysUser.getUserId()+""; // 在增加的位置赋值需要添加的数据
        }
        conferenceArrange1.setUserIds(ids);
        String[] userIds = conferenceArrange1.getUserIds();
        List<CommonUserVO> list = null;

        if(CommonConstants.AllUSER.equals(releaseScope)){
            list = commonMapper.listActiveUser(null,null);
        }else{
            list = commonMapper.listActiveUserByIds(userIds);
        }
        if(StringUtils.isNotNull(list)) {
            if (StringUtils.equals(CommonConstants.PUBLISHED, conferenceArrange1.getStatus())) {
                //短信提示
                if (StringUtils.equals(CommonConstants.TIPS, conferenceArrange1.getSmsTips())) {
                    AsyncManager.me().execute(createSmsTips(conferenceArrange1.getArrangeName(), list,conferenceArrange1));
                }
                //平台提示
                if (StringUtils.equals(CommonConstants.TIPS, conferenceArrange1.getWebsiteTips())) {
                    AsyncManager.me().execute(createWebsiteTips(list, 1));
                }
            }
        }
        conferenceArrangeService.updateConferenceArrange(conferenceArrange);
        return toAjax(conferenceArrangeService.updateStatusByArrangeId(conferenceArrange.getArrangeId(), CommonConstants.DRAFT));
    }

    /**
     * 删除会议安排
     */
    @RequiresPermissions("conference:arrange:remove")
    @Log(title = "会议安排", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(conferenceArrangeService.deleteConferenceArrangeByIds(ids));
    }

    /**
     * 发布会议安排
     */
    //@RequiresPermissions("conference:arrange:release")
    @Log(title = "发布会议安排", businessType = BusinessType.UPDATE)
    @PostMapping("/release")
    @ResponseBody
    @Transactional
    public AjaxResult release(Long arrangeId)
    {
        return toAjax(conferenceArrangeService.updateStatusByArrangeId(arrangeId, CommonConstants.DRAFT));
    }

    /**
     * 撤销工作
     */
    //@RequiresPermissions("conference:arrange:withdraw")
    @Log(title = "撤销会议安排", businessType = BusinessType.UPDATE)
    @PostMapping("/withdraw")
    @ResponseBody
    @Transactional
    public AjaxResult withdraw(Long arrangeId)
    {
        ConferenceArrange conferenceArrange = conferenceArrangeService.selectConferenceArrangeById(arrangeId);
        //会议主题
        String arrangeTheme = conferenceArrange.getArrangeTheme();
        //开始时间
        Date startTime = conferenceArrange.getStartTime();
        //结束时间
        Date endTime = conferenceArrange.getEndTime();
        //会议报名截止时间
        Date lastFullTime = conferenceArrange.getLastFullTime();
        //会议发起部门
        String deptName = conferenceArrange.getDeptName();

        String releaseScope = conferenceArrange.getReleaseScope();
        if ("1".equals(conferenceArrange.getSmsTips())){
            String[] userNames = releaseScope.split(" ");
            for (int i=0;i<userNames.length;i++) {
                String userName=userNames[i];
                SysUser sysUser = sysUserService.selectUserByName(userName);
                //发送对象的手机号
                @Size(min = 0, max = 11, message = "手机号码长度不能超过11个字符") String phonenumber = sysUser.getPhonenumber();
                String sms=userName+":您好！在线监督平台提示:由"+deptName+"部门发起的主题为:"+arrangeTheme+"的会议已取消！";
                SmsUtil.sendMessage(sms,phonenumber);
            }
        }
        return toAjax(conferenceArrangeService.updateStatusByArrangeId(arrangeId, CommonConstants.ENABLE));
    }


    private TimerTask createSmsTips(String arrangeTitle, List<CommonUserVO> list, ConferenceArrange conferenceArrange) {
        return new TimerTask()
        {
            @Override
            public void run()
            {
                for (CommonUserVO commonUserVO : list) {
                    String message = commonUserVO.getUserName()+"，您好！在线监督平台提示:由"+conferenceArrange.getDeptName()+"部门发起的会议标题为:"+arrangeTitle+"会议已更改，具体事宜请注意后续通知！";
                    String mobileNo = commonUserVO.getPhonenumber();
                    if(StringUtils.isNotEmpty(mobileNo)){
                        SmsUtil.sendMessage(message, mobileNo);
                    }
                }
            }
        };
    }

    private TimerTask createWebsiteTips(List<CommonUserVO> list, int num) {
        return new TimerTask()
        {
            @Override
            public void run()
            {
                for (CommonUserVO commonUserVO : list) {
                    WorkHandle workHandle = new WorkHandle();
                    workHandle.setUserId(commonUserVO.getUserId());
                    workHandle.setType(CommonConstants.WORK);
                    workHandleService.insertOrUpdateWorkHandle(workHandle, num); //工作项+1
                }
            }
        };
    }

}
